package com.zhfi.dataapply.config.quartz.company;

import com.zhfi.dataapply.entity.data.po.company.SoftwareCopyrightPO;
import com.zhfi.dataapply.mapper.company.SoftwareCopyrightMapper;
import com.zhfi.dataapply.schedule.reader.company.SoftwareCopyrightReader;
import com.zhfi.dataapply.schedule.writer.GeneralWriter;
import com.zhfi.dataapply.util.JobUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Slf4j
@Configuration
public class SoftwareCopyrightConfig implements JobExecutionListener {

    public static String JOB_NAME = "softwareCopyright";

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobUtil jobUtil;

    @Autowired
    private SoftwareCopyrightReader reader;

    @Autowired
    private SoftwareCopyrightMapper mapper;

    @Bean
    public Job softwareCopyrightJob() {
        return jobBuilderFactory.get(JOB_NAME + "Job")
                .listener(this)
                .start(softwareCopyrightStep())
                .build();
    }

    @Bean
    public Step softwareCopyrightStep() {
        return stepBuilderFactory.get(JOB_NAME + "Step")
                .<SoftwareCopyrightPO, SoftwareCopyrightPO>chunk(20)
                .reader(reader)
                .writer(softwareCopyrightWriter())
                .build();
    }

    @Bean
    public ItemWriter<SoftwareCopyrightPO> softwareCopyrightWriter() {
        return new GeneralWriter<>(mapper);
    }

    @Override
    public void beforeJob(JobExecution jobExecution) {
        reader.reset();
        jobUtil.doJobStart(JOB_NAME);
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        jobUtil.doJobEnd(JOB_NAME, jobExecution);
    }

}
